xquery version "1.0";
(: $Id: devguide_xquery.xml 15318 2011-09-07 19:43:24Z dizzzz application/xquery $ :)

import module namespace request="http://exist-db.org/xquery/request";
import module namespace session="http://exist-db.org/xquery/session";
import module namespace util="http://exist-db.org/xquery/util";
import module namespace  fn="http://www.w3.org/2005/xpath-functions";

declare option exist:serialize "method=xhtml media-type=text/xml";

declare function local:random($max as xs:integer) 
as empty()
{
    let $r := ceiling(util:random() * $max) cast as xs:integer
    return (
        session:set-attribute("random", $r),
        session:set-attribute("guesses", 0)
    )
};

declare function local:guess($guess as xs:integer,
$rand as xs:integer) as element()
{
    let $count := session:get-attribute("guesses") + 1
    return (
        session:set-attribute("guesses", $count),
        if ($guess lt $rand) then
            <p>Your number is too small!</p>
        else if ($guess gt $rand) then
            <p>Your number is too large!</p>
        else
            let $newRandom := local:random(100)
            return
                <p>Congratulations! You guessed the right number with
                {$count} tries. Try again!</p>
    )
};

declare function local:main() as node()?
{
    session:create(),
    let $rand := session:get-attribute("random"),
        $guess := xs:integer(request:get-parameter("guess", ()))
    return
		if ($rand) then 
			if ($guess) then
				local:guess($guess, $rand)
			else
				<p>No input!</p>
		else 
		    local:random(100)
};

declare function local:myFirstTest() as node()?
{
	let $n1 := request:get-parameter("n1", "")
	return <p>n1 = {$n1}</p>
};

declare function local:testIfIsfet() as element()*
{
	let $uri := request:get-parameter("uri_api", "")
	return 
		if (fn:contains($uri, "ISFET")) then
			<alert><type>jms</type> <content-type>text/plain</content-type> <destination> ME </destination> <msg> This is isfet !!</msg></alert>
		else 
			()
};

declare function local:test() as element()*
{
	let $uri := request:get-parameter("uri_api", "")
	return 
		
		<alert><type>jms</type> <content-type>text/plain</content-type> <destination> ME </destination> <msg> uri: {$uri}</msg></alert>
		
};

<GeneratedAlerts>
	<memory>aaa</memory>
	<alerts>
		{local:test()}
	</alerts>
</GeneratedAlerts>
